package edu.nus.mtech.sem1.ca.main;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import edu.nus.mtech.sem1.ca.cust.Customer;
import edu.nus.mtech.sem1.ca.cust.complaint.Complaint;
import edu.nus.mtech.sem1.ca.exception.CustomerNotFoundException;
import edu.nus.mtech.sem1.ca.main.dao.TelephonyApplicationDao;
import edu.nus.mtech.sem1.ca.utils.Common;
import edu.nus.mtech.sem1.ca.utils.Logger;
import edu.nus.mtech.sem1.ca.utils.TelephonyConstants;
import edu.nus.mtech.sem1.ca.utils.TelephonyUtils;

/**
 * List window which wraps the Complaints JTable. Looks really cool
 *
 */
public class FormAllComplaints extends JInternalFrame {
	private JTable table;
	private JTextField textField;
	private TelephonyApplicationDao telephoneDao=new TelephonyApplicationDao();

	private JTextField txtSearchInput;
	private ArrayList<Customer> l_cusArray;
	private Vector<Customer> columnHeader;
	private Vector<String> columnData;
	private JLabel messageLabel; 
	/**
	 * Create the panel.
	 */
	public FormAllComplaints() {
		initialize();
		setTitle("Complaints List");
	}

	public FormAllComplaints(String nric, String customerName) {
		initialize();
		setTitle("Complaints of "+customerName);
		Set<Complaint> searchComplaints = searchComplaints(nric);
		Vector columnHeader=getColumnHeaderForComplaint();
		Vector columnData=getColumnDataFromComplaintsObjects(searchComplaints);
		table.setModel(new TelephonyJTableModel(columnHeader, columnData));
	}

	private void initialize() {
		
		setClosable(true);
		setBounds(100, 100, 907, 494);
		getContentPane().setLayout(null);
		
		JLabel lblSearchBy = new JLabel("Search By NRIC");
		lblSearchBy.setBounds(11, 15, 135, 14);
		getContentPane().add(lblSearchBy);
		
		txtSearchInput = new JTextField();
		txtSearchInput.setBounds(200, 10, 164, 20);
		txtSearchInput.setToolTipText("Clear text box for full search");
		getContentPane().add(txtSearchInput);
		txtSearchInput.setColumns(50);
		
		
		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				if (txtSearchInput.getText()!=null){
					Set<Complaint> complaints=searchComplaints(txtSearchInput.getText().toUpperCase());
					Vector columnHeader=getColumnHeaderForComplaint();
					Vector columnData=getColumnDataFromComplaintsObjects(complaints);
					table.setModel(new TelephonyJTableModel(columnHeader, columnData));
				}
				
			}
		});
		btnSearch.setBounds(418, 12, 89, 23);
		getContentPane().add(btnSearch);
		
		//LoadCustomers();
		
		//NRIC hardcoded for sample data
		Set<Complaint> complaintsForDummyClient=null;
		complaintsForDummyClient = telephoneDao.retrieveComplaintsForCustomer("P777777");
		Vector columnHeader=getColumnHeaderForComplaint();
		Vector columnData=getColumnDataFromComplaintsObjects(complaintsForDummyClient);
		Logger.log("column header : "+columnHeader);
		Logger.log("column data: "+columnData);
		TelephonyJTableModel customerTableModel = new TelephonyJTableModel(columnHeader, columnData);
		table = new JTable(customerTableModel);
		
		//getContentPane().add(table);
		
		JButton btnSelect = new JButton("Select");
		btnSelect.setBounds(11, 431, 104, 23);
		getContentPane().add(btnSelect);
		
		btnSelect.addActionListener(new ComplaintSelectActionListener());
		
		
		DefaultTableModel headerData = new DefaultTableModel(0, 1);
		headerData.addRow(columnHeader.toArray()); 
        JTable rowHeader = new JTable(new DefaultTableModel(
        	new Object[][] {
        	},
        	new String[] {
        	}
        ));

      /*  LookAndFeel.installColorsAndFont
            (rowHeader, "TableHeader.background", 
            "TableHeader.foreground", "TableHeader.font");
*/
        
        rowHeader.setIntercellSpacing(new Dimension(0, 0));
        Dimension d = rowHeader.getPreferredScrollableViewportSize();
        d.width = rowHeader.getPreferredSize().width;
        rowHeader.setPreferredScrollableViewportSize(d);
        rowHeader.setRowHeight(table.getRowHeight());
        
        JScrollPane scrollPane = new JScrollPane(table);
        
        scrollPane.setRowHeaderView(rowHeader);

        JTableHeader corner = rowHeader.getTableHeader();
        corner.setReorderingAllowed(false);
        corner.setResizingAllowed(false);

        scrollPane.setBounds(11, 43, 869, 379);
        scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, corner);
        scrollPane.setVisible(true);


        getContentPane().add(scrollPane, BorderLayout.CENTER);
        
        messageLabel = new JLabel("");
        messageLabel.setBounds(537, 15, 343, 20);
        getContentPane().add(messageLabel);
        
        JButton btnCustomers = new JButton("Customers");
        btnCustomers.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent arg0) {
        		FormAllCustomers allCustomers=new FormAllCustomers();
				getParent().add(allCustomers);
				Common.OpenCenterScreen(allCustomers, true);
				setVisible(false);
				dispose();
        	}
        });
        btnCustomers.setBounds(733, 431, 147, 23);
        getContentPane().add(btnCustomers);
	}


	/**
	 * Returns the header for the JTable
	 * @param headerCustomer
	 * @return
	 */
	private Vector<String> getColumnHeaderForComplaint() {
		Vector<String> headerList=new Vector<String>();
		//Ah. just for a change. let's use a tokenizer
		StringTokenizer tokenizer=new StringTokenizer(TelephonyConstants.HEADER_COMPLAINTS, TelephonyConstants.SEMICOLON);
		
		for(String tempString; tokenizer.hasMoreTokens();){
			tempString=tokenizer.nextToken();
			headerList.add(tempString);
		}
		Logger.log("Header list "+headerList);
		return headerList;
	}
		
	private Vector<Vector> getColumnDataFromComplaintsObjects(Set<Complaint> complaints) {
		
		Vector<Vector> columnData=new Vector<Vector>();
		Vector<String> eachColumnData=null;
		
		if (complaints==null){
			eachColumnData=getEmptyComplaintList();
			columnData.add(eachColumnData);
			return columnData;
		}
		for (Complaint eachComplaint:complaints){
			
			if (eachComplaint!=null){
				eachColumnData=new Vector<String>();
				eachColumnData.add(eachComplaint.getNric());
				eachColumnData.add(eachComplaint.getAccountNo());
				eachColumnData.add(eachComplaint.getService().toString());
				eachColumnData.add(eachComplaint.getComplaintNo());
				eachColumnData.add(TelephonyUtils.getStringFromDate(eachComplaint.getComplaintDate()));
				eachColumnData.add(eachComplaint.getComplaintDesc().toString());
				eachColumnData.add(eachComplaint.getStatus().toString());
				
				columnData.add(eachColumnData);
				Logger.log("column data "+columnData);
			}
			
		}
		
		return columnData;
	}
	

	private Vector<String> getEmptyComplaintList() {
		Vector<String> eachColumnData=new Vector<String>();
		eachColumnData.add("");
		eachColumnData.add("");
		eachColumnData.add("");
		eachColumnData.add("");
		eachColumnData.add("");
		eachColumnData.add("");
		eachColumnData.add("");
		return eachColumnData;
	}


	/**
	 * Retrieves complaints for a customer
	 * @param nric
	 * @return
	 * @throws CustomerNotFoundException
	 */
	private Set<Complaint> searchComplaints(String nric){
		Set<Complaint> complaints =null;
		if (nric==null || nric.trim().equals("")){
			messageLabel.setText(TelephonyConstants.ERR_ENTER_NRIC);
		}
		else{
			complaints= telephoneDao.retrieveComplaintsForCustomer(nric);
		}
		return complaints;
	}

	
	/**
	 * This one is tricky. This event gets the nric and the complaint number and gets the complaint for a customer. Sweet.
	 *
	 */
	private class ComplaintSelectActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent actionEvent) {

				 //JTable jtable = (JTable) mouseEvent.getSource();
			     int selection= table.getSelectedRow();
			     Logger.log("Selected row "+selection);
			     table.clearSelection();
			     try {
					Logger.log(table.getModel().getValueAt(selection, 0));
					 
					 String nric=(String) table.getModel().getValueAt(selection, 0);
					 Customer customer=telephoneDao.retrieveCustomerData(nric);
					 String complaintNo=(String) table.getModel().getValueAt(selection, 3);
					 Logger.log("Nric : "+nric);
					 Logger.log("Complaint no: "+complaintNo);
					 setVisible(false);
					 FormComplaint frmComplaintObj=new FormComplaint(nric, complaintNo, customer.getName());
					 for (java.awt.Component var : getParent().getComponents()) {
							if(var instanceof FormComplaint){
								var.setVisible(false);
								if(var instanceof JInternalFrame){
									((JInternalFrame)var).dispose();
								}
							}
						}
					 
					 getParent().add(frmComplaintObj);
					 Common.OpenCenterScreen(frmComplaintObj, true);
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, TelephonyConstants.ERR_SELECT_A_ROW, "Info", JOptionPane.INFORMATION_MESSAGE);
					//e.printStackTrace();
				}
				finally{
					dispose();
				}
		}
		
	}
}
